<?php
/**
 * Created by PhpStorm.
 * User: liuxin
 * Date: 2018/1/12
 * Time: 下午2:14
 */

namespace common\components;

use yii\web\UnauthorizedHttpException;

class RedisToken
{
    public static $_instance;

    private function __construct()
    {
        # code...
    }
    private function __clone()
    {
        # empty
    }
    public static function Instance()
    {
        if(!(self::$_instance instanceof self))
        {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function createToken($user_guid,$app_id, $device)
    {
        $key = 't_' . $user_guid;
        $token = strtoupper(Helper::create_union_id('t'));
        Factory::Redis()->hset($key, $app_id . '_' . $device, $token);
        Factory::Redis()->expire($key, TOKEN_EXPIRE_TIME);
        return $token;
    }

    public function createTokenLongByPc($pcIp,$machineCode,$token,$userGuid){
        $key = 't_' . $pcIp . "_" . $machineCode;
        Factory::Redis()->set($key.'_'.$token,$userGuid);
        Factory::Redis()->expire($key, TOKEN_EXPIRE_TIME);
        return $token;
    }

    public function createTokenByPc($ip, $device,$unique,$userGuid)
    {
        $key = 't_' . $ip . "_" . $device . "_". $unique;
        $token = strtoupper(Helper::create_union_id('t'));
        Factory::Redis()->hset($key,$token,$userGuid);
        Factory::Redis()->expire($key, ONE_MINITE_SECONDS);
        return $token;
    }

    public function checkAccessToken($user_guid,$app_id,$device,$token){
        $tmp_token = $this->getToken($user_guid,$app_id,$device);
        if($tmp_token === $token)
            return $token;
        else
            return false;
    }

    public function checkAccessTokenByPc($pc_ip,$machine_code,$token){
        $key = 't_' . $pc_ip . "_" . $machine_code.'_'.$token;
        $user_guid = Factory::Redis()->get($key);
        if(empty($user_guid)){
            return false;
        }
        return $user_guid;
    }

    public function getToken($user_guid,$app_id,$device){
        $key = 't_'.$user_guid;
        $ret = Factory::Redis()->hget($key,$app_id.'_'.$device);
        if(empty($ret)){
            return false;
        }
        return $ret;
    }

    public function getTokenByPc($ip,$device,$unique){
        $key = 't_' . $ip . "_" . $device . "_". $unique;
        $ret = Factory::Redis()->hgetall($key);
        if(empty($ret)){
            return false;
        }
        Factory::Redis()->del($key);
        return $ret;
    }

}